import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import './index.scss'
import { useTranslation } from 'react-i18next'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import {
  articleGetArticleDetailService,
  articlePublishService,
  articleUpdateArticleService
} from '@/api/article'
import { useState } from 'react'
import { message } from 'antd'
import { useChannel } from '@/hooks/useChannel'
import { useEffect } from 'react'
import { useSearchParams } from 'react-router-dom'

const { Option } = Select

const Publish = () => {
  //国际化
  const { t } = useTranslation()
  //获取频道列表
  const { channelList } = useChannel()
  // 控制图片Type
  const [imageType, setImageType] = useState(0)
  const changeIamgeType = (e) => {
    setImageType(e.target.value)
  }
  //图片上传
  const [imageList, setImageList] = useState([])
  const onUploadChange = (info) => {
    console.log(info.fileList)
    setImageList(info.fileList)
  }
  //表单提交
  const onFinish = async (formValue) => {
    const { title, channel_id, content } = formValue
    if (imageType !== 0 && imageList.length !== imageType)
      return message.warning(t('content.publish.form.imageCountError'))
    const reqData = {
      title,
      channel_id,
      cover: {
        type: imageType,
        images: imageList.map((item) => {
          if (item.response) {
            return item.response.data.url
          } else {
            //编辑文章时，图片回显的图片列表格式不一样，需要做处理，如果是回显的图片，在该处处理
            return item.url
          }
        })
      },
      content
    }
    if (!articleId) {
      await articlePublishService(reqData)
      message.success(t('content.publish.form.success'))
    } else {
      await articleUpdateArticleService({
        ...reqData,
        id: articleId
      })
      message.success(t('content.publish.form.editSuccess'))
    }
  }
  //数据回显
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')
  const [form] = Form.useForm()
  useEffect(() => {
    const fetchArticle = async () => {
      const res = await articleGetArticleDetailService(articleId)
      form.setFieldsValue({ ...res.data, type: res.data.cover.type })
      setImageType(res.data.cover.type)
      setImageList(res.data.cover.images.map((item) => ({ url: item })))
    }
    //编辑文章数据回显
    if (articleId) {
      fetchArticle()
    }
  }, [articleId, form])

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb
            items={[
              {
                title: (
                  <Link to={'/'}>{t('content.publish.breadCrumb.home')}</Link>
                )
              },
              {
                title: `${articleId ? t('content.publish.breadCrumb.edit') : t('content.publish.breadCrumb.publish')}`
              }
            ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label={t('content.publish.form.title')}
            name="title"
            rules={[
              {
                required: true,
                message: t('content.publish.form.titlePlaceholder')
              }
            ]}
          >
            <Input
              placeholder={t('content.publish.form.titlePlaceholder')}
              style={{ width: 400 }}
            />
          </Form.Item>
          <Form.Item
            label={t('content.publish.form.channel')}
            name="channel_id"
            rules={[
              {
                required: true,
                message: t('content.publish.form.channelPlaceholder')
              }
            ]}
          >
            <Select
              placeholder={t('content.publish.form.channelPlaceholder')}
              style={{ width: 400 }}
            >
              {channelList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label={t('content.publish.form.cover')}>
            <Form.Item name="type">
              <Radio.Group onChange={changeIamgeType}>
                <Radio value={1}>{t('content.publish.form.singleCover')}</Radio>
                <Radio value={3}>{t('content.publish.form.threeCover')}</Radio>
                <Radio value={0}>{t('content.publish.form.noCover')}</Radio>
              </Radio.Group>
            </Form.Item>
            {imageType !== 0 && (
              <Upload
                listType="picture-card"
                showUploadList
                onChange={onUploadChange}
                maxCount={imageType}
                name="image"
                action={'http://geek.itheima.net/v1_0/upload'}
                fileList={imageList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label={t('content.publish.form.content')}
            name="content"
            rules={[
              {
                required: true,
                message: t('content.publish.form.contentPlaceholder')
              }
            ]}
          >
            {/* 富文本编辑器 */}
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder={t('content.publish.form.contentPlaceholder')}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {t('content.publish.form.button')}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
